package com.kgar.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kgar.dao.LoginDao;
import com.kgar.dto.LoginFormDTO;
import com.kgar.dto.Result;
import com.kgar.dto.UserDTO;
import com.kgar.entity.pojo.Login;
import com.kgar.entity.pojo.User;
import com.kgar.service.AsyncService;
import com.kgar.service.LoginService;
import com.kgar.service.UserService;
import com.kgar.util.RegexUtils;
import com.kgar.util.AlibabaSmsUtil;
import com.kgar.util.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.kgar.util.RedisConstants.*;
import static com.kgar.util.SystemConstants.USER_NAME_PREFIX;

@Slf4j
@Service
public class LoginServiceImpl extends ServiceImpl<LoginDao, Login> implements LoginService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private AlibabaSmsUtil alibabaSmsUtil;

    @Resource
    private AsyncService asyncService;

    @Override
    public Result login(LoginFormDTO loginForm) {
        //校验手机号
        String phone = loginForm.getTelephone();
        //获取密码
        String password = loginForm.getPassword();
        if (password != null) {
            //获取数据库中的密码
            User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getTelephone, phone));
            if(user==null){
                return Result.fail("用户不存在，请先注册");
            }
            Integer userId = user.getUserId();
            Login byId = getById(userId);
            if (byId == null) {
                return Result.fail("手机号不正确或密码错误");
            }
            //校验密码
            String md5Pwd = DigestUtil.md5Hex(password);
            String pwd = byId.getPassword();
            if (!pwd.equals(md5Pwd)) {
                return Result.fail("密码不正确");
            }
        } else {
            //获取验证码
            String code = stringRedisTemplate.opsForValue().get(PHONE_CODE_KEY + phone);
            if (code == null) {
                return Result.fail("手机号不正确或验证码过期");
            }
            //校验验证码
            if (!loginForm.getCode().equals(code)) {
                //不一致，报错
                return Result.fail("验证码不正确");
            }
        }
        return saveInfo(phone);
    }

    private Result saveInfo(String phone) {
        //根据手机号查询用户
        User user = userService.query().eq("telephone", phone).one();
        //判断用户是否存在
        if (user == null) {
            //不存在，创建新用户，并保存数据库
            user = createUserWithPhone(phone);

        }

        //获取随机uuid
        String token = UUID.randomUUID().toString(true);
        String tokenKey = LOGIN_USER_KEY + token;
        //保存用户信息到Redis
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil
                .beanToMap(userDTO, new HashMap<>(),
                        CopyOptions.create().setIgnoreNullValue(true)
                                .setFieldValueEditor(
                                        (fieldName, fieldValue) -> fieldValue.toString()
                                ));
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);

        //设置有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.SECONDS);

        //保存到知识图谱
        asyncService.createUserNode(userDTO);

        return Result.ok(token);
    }

    @Override
    public Result sendCode(String phone) {
        //校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //如果不符合，返回错误信息
            return Result.fail("手机号格式错误");
        }
        //符合就生成验证码
        String code = RandomUtil.randomNumbers(6);

        //保存验证码到redis
        stringRedisTemplate.opsForValue().set(PHONE_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);

        String message ;
        //发送短信验证码
        try {
            message = alibabaSmsUtil.sendSms(phone, MapUtil.of("code",code));
            //打印信息
            log.info(message);
            //若发送失败,返回错误信息
            if (!message.equals("OK"))
                return Result.fail(message);
            //打印成功信息到控制台
            log.info("已发送到手机号:"+phone);
            log.debug("发送短信验证码成功，验证码：" + code);
            //返回成功
            return Result.ok();
        } catch (Exception e) {
            log.error("发送短信验证码失败!");
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result logout(String authorization) {
        UserHolder.removeUser();
        stringRedisTemplate.delete(LOGIN_USER_KEY+authorization);
        return Result.ok();
    }


    @Override
    public Result setPassword(LoginFormDTO loginFormDTO) {
        //获取手机号
        String phone = loginFormDTO.getTelephone();
        //获取验证码
        String code = loginFormDTO.getCode();
        //获取密码
        String password = loginFormDTO.getPassword();

        Integer userId = UserHolder.getUser().getUserId();
        //获取当前用户的手机号
        User one = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserId, userId));

        String userPhone = one.getTelephone();

        //判断是否是当前用户的手机号
        if (!Objects.equals(userPhone, phone)) {
            return Result.fail("手机号错误");
        }

        //获取redis中的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(PHONE_CODE_KEY + phone);

        if (!code.equals(redisCode)) {
            return Result.fail("验证码错误");
        }

        //走到这一步说明可以保存密码了，先加密密码
        String md5Pwd = DigestUtil.md5Hex(password);

        Login login = new Login();
        login.setUserId(userId);
        login.setPassword(md5Pwd);
        boolean b = saveOrUpdate(login);

        return b? Result.ok():Result.fail("系统繁忙");

    }


    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setTelephone(phone);
        user.setUserName(USER_NAME_PREFIX + RandomUtil.randomString(10));
        user.setRegistrationDate(DateTime.now());
        userService.save(user);
        return user;
    }
}
